import { FC, ReactNode } from 'react'
import ReactMarkdown, { Components } from 'react-markdown'
import rehypeHighlight from 'rehype-highlight'
import { Terminal } from 'lucide-react'
import 'highlight.js/styles/atom-one-dark.css'
import CopyButton from './CopyButton'
import { visit } from 'unist-util-visit'
import remarkDirective from 'remark-directive'
import { Node, Data } from 'unist'
import { Root, Content } from 'mdast'

// 扩展 Directive 节点类型
type Directive = Content & {
  type: 'textDirective' | 'leafDirective' | 'containerDirective'
  name: string
  attributes?: Record<string, string | number | boolean>
  data?: Data
}

// 扩展 Code 节点类型
interface CodeNode extends Node {
  lang?: string
  meta?: string
  data?: Data & {
    meta?: string
  }
}

const remarkCustomDirectives = () => {
  return (tree: Root) => {
    visit<Root, Directive>(tree, (node: any) => {
      if (
        node.type === 'textDirective' ||
        node.type === 'leafDirective' ||
        node.type === 'containerDirective'
      ) {
        if (node.name === 'think') {
          node.data = {
            ...node.data,
            hName: 'ThinkBlock',
            hProperties: {},
          }
        }
      }
    })
  }
}
const replaceThink = (str: string) => {
  try {
    return str
      .replace(/<think[^>]*>/gi, '\n:::think\n')
      .replace(/<\/think>/gi, '\n:::\n')
  } catch (error) {
    console.error('Error replacing think:', error)
    return str
  }
}

const ThinkBlock: FC<{ children?: ReactNode }> = ({ children }) => (
  <details open className="mb-4 max-w-full break-words">
    <summary className="text-sm text-gray-400 cursor-default ml-2">
      思考
    </summary>
    <div className="mt-1 text-sm text-gray-500 border-l-2 border-gray-300 pl-3 ml-3">
      {children}
    </div>
  </details>
)

const Markdown: FC<{ content: string }> = ({ content }) => {
  const str = replaceThink(content)
  return (
    <div className=" break-words h-auto">
      <ReactMarkdown
        remarkPlugins={[remarkDirective, remarkCustomDirectives]}
        rehypePlugins={[rehypeHighlight]}
        components={
          {
            ThinkBlock,
            pre: ({ children }) => <pre className="not-prose">{children}</pre>,
            a: ({ node, ...props }) => {
              return (
                <a
                  {...props}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{ color: '#409EFF', textDecoration: 'underline' }}
                >
                  {props.children}
                </a>
              )
            },
            code: ({ node, className, children, ...props }) => {
              const codeNode = node as CodeNode
              const match = /language-(\w+)/.exec(className || '')
              if (match) {
                const lang = match[1]
                const id = `code-${Math.random().toString(36).substr(2, 9)}`
                return (
                  <div className="not-prose overflow-x-auto rounded-md border border-zinc-200 dark:border-zinc-700">
                    <div className="flex h-10 items-center justify-between bg-zinc-100 px-4 dark:bg-zinc-900">
                      <div className="flex items-center gap-2">
                        <Terminal size={18} />
                        <p className="text-xs text-zinc-600 dark:text-zinc-400">
                          {codeNode?.data?.meta || lang}
                        </p>
                      </div>
                      <CopyButton id={id} />
                    </div>
                    <div className="overflow-x-auto w-full text-xs">
                      <div id={id} className="p-4 min-w-[100%] text-sm">
                        <code className={className} {...props}>
                          {children}
                        </code>
                      </div>
                    </div>
                  </div>
                )
              }

              return (
                <code
                  {...props}
                  className="not-prose   text-xs rounded bg-gray-100 px-1"
                >
                  {children}
                </code>
              )
            },
          } as Components
        }
      >
        {str}
      </ReactMarkdown>
    </div>
  )
}

export default Markdown
